package com.bjsxt.commu4;

/**
 * 测试类
 */
public class Test {

    public static void main(String[] args) {

        //保证生产者和消费者之间，使用同一个工厂对象
        ProductFactory factory = new ProductFactory(30);      //final可省略

        //创建10个生产者线程并启动最好使用notifyAll，防止唤醒到
        //Runnable produceRunnable = new ProduceRunnable(factory);
        Runnable produceRunnable = new Runnable() {
            @Override
            public void run() {
                int i = 0;

                while (true) {
                    //生成一件产品
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    factory.produce("产品" + i);
                    i++;
                }
            }
        };
        for (int i = 1; i <= 10; i++) {
            new Thread(produceRunnable, "生产者" + i).start();
        }

        //创建20个消费者线程并启动
        //Runnable consumeRunnable = new ConsumeRunnable(factory);
        Runnable consumeRunnable = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //消费一件产品
                    factory.consume();
                }
            }
        };
        for (int i = 1; i <= 20; i++) {
            new Thread(consumeRunnable, "消费者" + i).start();
        }

    }
}
